import React, { useState, useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import INavLink from '../INavLink'
import axios from 'axios'

import './index.css'

function Header(props) {
  const { pathname } = props.location
  // 菜单
  const [menu, setMenu] = useState([])

  const [isOn, setIsOn] = useState(pathname.substring(0, pathname.indexOf('/', 1)))
  // console.log(isOn, pathname)

  const getMenu = async () => {
    const res = await axios({ url: '/menu', method: 'get' })
    const { data, status } = res
    if (status === 200) {
      setMenu(data.data)
    }
  }

  const showMenu2 = (isOn) => {
    const { children } = menu.find((v) => v.linkUrl === isOn) || {}
    if (children) {
      return children.map((v) => (
        <li className='hd_menu2_item' key={v.id}>
          <INavLink activeClassName='active' to={v.linkUrl}>
            {v.name}
          </INavLink>
        </li>
      ))
    }
  }

  useEffect(() => {
    getMenu()
  }, [])

  useEffect(() => {
    setIsOn(pathname.substring(0, pathname.indexOf('/', 1)))
  }, [pathname])

  return (
    <div className='page-header hd'>
      <ul className='hd_menu1'>
        {menu.map((v) => (
          <li
            className={isOn === v.linkUrl ? 'hd_menu1_item on' : 'hd_menu1_item'}
            key={v.id}
            name={v.id}
            onClick={() => setIsOn(v.linkUrl)}
          >
            {v.name}
          </li>
        ))}
      </ul>
      <ul className='hd_menu2'>{menu.length > 0 ? showMenu2(isOn) : null}</ul>
    </div>
  )
}

export default withRouter(Header)
